package com.ovopark.organize.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ovopark.organize.server.common.exception.CommonException;
import com.ovopark.organize.server.common.support.LocalStorageUtils;
import com.ovopark.organize.server.mapper.FranchiseesApprovalTemplateGroupMapper;
import com.ovopark.organize.server.mapper.FranchiseesApprovalTemplateMapper;
import com.ovopark.organize.server.mapper.FranchiseesApprovalTemplateSectionMapper;
import com.ovopark.organize.server.model.entity.*;
import com.ovopark.organize.server.service.*;
import com.ovopark.organize.server.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * @author wxb
 * @Title: FranchiseesApprovelServiceImpl
 * @Description: 加盟商立项模板
 * @date 2024/4/11 15:51
 **/
@Service
@Slf4j
public class FranchiseesApprovalTemplateServiceImpl extends ServiceImpl<FranchiseesApprovalTemplateMapper, FranchiseesApprovalTemplate> implements FranchiseesApprovalTemplateService {

    @Resource
    private FranchiseesApprovalTemplateSectionService franchiseesApprovalTemplateSectionService;

    @Resource
    private FranchiseesApprovalTemplateFieldService franchiseesApprovalTemplateFieldService;

    @Resource
    private FranchiseesApprovalTemplateSectionMapper franchiseesApprovalTemplateSectionMapper;

    @Resource
    private FranchiseesApprovalTemplateUserService franchiseesApprovalTemplateUserService;

    @Resource
    private FranchiseesApprovalTemplateFieldValueService franchiseesApprovalTemplateFieldValueService;

    @Resource
    private FranchiseesApprovalTemplateGroupMapper franchiseesApprovalTemplateGroupMapper;

    @Resource
    private FranchiseesApprovalTemplateGroupService franchiseesApprovalTemplateGroupService;

    @Resource
    private UserService userService;

    @Resource
    private MessageSource messageSource;

    /**
     * @description: 创建模板
     * @param: [template]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate
     * @author wxb
     * @date: 2024/6/2 20:47
     */
    @Override
    public FranchiseesApprovalTemplate saveTemplate(FranchiseesApprovalTemplate template) {
        Locale locale = LocalStorageUtils.getStorageInfo().getLocale();
        // 参数模板id
        Integer templateId = template.getId();
        // 校验名称是否重复
        if (StringUtils.isNotEmpty(template.getTemplateName())) {
            List<FranchiseesApprovalTemplate> hasTemplateName = this.hasTemplateName(template.getGroupId(), template.getTemplateName());
            if (CollectionUtil.isNotEmpty(hasTemplateName)) {
                // 更新 去除自己
                if (templateId != null) {
                    List<Integer> templateIds = hasTemplateName.stream().map(FranchiseesApprovalTemplate::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(templateIds) && !templateIds.contains(templateId)) {
                        // 重名
                        String message = messageSource.getMessage("franchisees.approval.template.RESULT_DUPLICATE", null, locale);
                        throw new CommonException(message);
                    }
                } else {
                    // 新增 重名
                    String message = messageSource.getMessage("franchisees.approval.template.RESULT_DUPLICATE", null, locale);
                    throw new CommonException(message);
                }
            }
        }
        // 新增
        if (templateId == null) {
            return this.add(template);
        } else {
            // 修改
            return this.update(template);
        }
    }

    /**
     * @description: 新增
     * @param: [template]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate
     * @author wxb
     * @date: 2024/6/5 11:05
     */
    @Override
    public FranchiseesApprovalTemplate add(FranchiseesApprovalTemplate template) {
        this.baseMapper.insert(template);
        return template;
    }

    /**
     * @description: 编辑
     * @param: [template]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate
     * @author wxb
     * @date: 2024/6/5 11:05
     */
    @Override
    public FranchiseesApprovalTemplate update(FranchiseesApprovalTemplate template) {
        Integer groupId = template.getGroupId();
        Integer templateId = template.getId();
        // 获取模板
        FranchiseesApprovalTemplate existTemplate = this.getTemplateById(templateId, groupId);
        // 系统模板
        if (existTemplate.getGroupId() == null) {
            // 查询企业是否已经配置过
            FranchiseesApprovalTemplateGroup templateGroup = franchiseesApprovalTemplateGroupService.getGroupTemplate(groupId, template.getId());
            // 新增
            if (templateGroup == null) {
                templateGroup = new FranchiseesApprovalTemplateGroup();
                templateGroup.setTemplateId(templateId);
                templateGroup.setTemplateName(template.getTemplateName());
                templateGroup.setTemplateDesc(template.getTemplateDesc());
                templateGroup.setGroupId(groupId);
                templateGroup.setIsOpen(template.getIsOpen());
                templateGroup.setUpdateTime(LocalDateTime.now());
                templateGroup.setUpdateId(template.getUpdateId());
                franchiseesApprovalTemplateGroupMapper.insert(templateGroup);
            } else {
                // 修改
                templateGroup.setTemplateId(templateId);
                templateGroup.setTemplateName(template.getTemplateName());
                templateGroup.setTemplateDesc(template.getTemplateDesc());
                templateGroup.setGroupId(groupId);
                templateGroup.setIsOpen(template.getIsOpen());
                templateGroup.setUpdateTime(LocalDateTime.now());
                templateGroup.setUpdateId(template.getUpdateId());
                franchiseesApprovalTemplateGroupMapper.updateById(templateGroup);
            }
        } else {
            // 修改
            this.baseMapper.updateById(template);
        }
        return template;
    }

    /**
     * @description: 关闭模板
     * @param: [groupId]
     * @return: void
     * @author wxb
     * @date: 2024/6/2 20:48
     */
    @Override
    public void closeTemplate(Integer groupId) {
        if (groupId != null) {
            FranchiseesApprovalTemplate template = new FranchiseesApprovalTemplate();
            template.setGroupId(groupId);
            template.setIsOpen(0);
            LambdaQueryWrapper<FranchiseesApprovalTemplate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FranchiseesApprovalTemplate::getGroupId, groupId);
            queryWrapper.eq(FranchiseesApprovalTemplate::getIsOpen, 1);
            this.baseMapper.update(template, queryWrapper);
        }
    }

    /**
     * @description: 获取加盟商立项模板
     * @param: [id]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate
     * @author wxb
     * @date: 2024/6/1 13:04
     */
    @Override
    public FranchiseesApprovalTemplate getTemplateById(Integer id, Integer groupId) {
        if (id != null) {
            FranchiseesApprovalTemplate template = this.baseMapper.selectById(id);
            // 系统模板
            if (template.getGroupId() == null) {
                FranchiseesApprovalTemplateGroup templateGroup = franchiseesApprovalTemplateGroupService.getGroupTemplate(groupId, id);
                // 没有改过系统模板
                if (templateGroup != null) {
                    template.setTemplateName(templateGroup.getTemplateName());
                    template.setTemplateDesc(templateGroup.getTemplateDesc());
                    template.setIsOpen(templateGroup.getIsOpen());
                    template.setUpdateId(templateGroup.getUpdateId());
                    if (templateGroup.getUpdateId() != null) {
                        Users users = userService.getUsersById(templateGroup.getUpdateId());
                        template.setUpdateUser(users.getShowName());
                    }
                    template.setUpdateTime(templateGroup.getUpdateTime());
                }
            }
            return template;
        }
        return null;
    }

    /**
     * @description: 开启/关闭模版
     * @param: [id, open, groupId, userId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/2 21:00
     */
    @Override
    public Boolean onOffTemplate(Integer id, Integer open, Integer groupId, Integer userId) {
        try {
            // 查询模板
            FranchiseesApprovalTemplate template = this.getTemplateById(id, groupId);
            if (template == null) {
                throw new CommonException("模板不存在");
            }
            // 企业开启的模板
            FranchiseesApprovalTemplate defaultTemplate = this.getDefaultTemplate(groupId);
            if (defaultTemplate != null && defaultTemplate.getGroupId() == null && defaultTemplate.getId().equals(id) && open != null && open.equals(0)) {
                throw new CommonException("系统模板不能关闭");
            }
            if (open != null && open.equals(1)) {
                // 把已经开启的关闭
                this.closeTemplate(groupId);
                franchiseesApprovalTemplateGroupService.closeTemplate(groupId);
            }
            if (template.getGroupId() == null) {
                // 系统模板
                FranchiseesApprovalTemplateGroup templateGroup = franchiseesApprovalTemplateGroupService.getGroupTemplate(groupId, id);
                templateGroup.setIsOpen(open);
//                templateGroup.setUpdateId(userId);
//                templateGroup.setUpdateTime(LocalDateTime.now());
                franchiseesApprovalTemplateGroupMapper.updateById(templateGroup);
            } else {
                // 企业模板
                template.setIsOpen(open);
//                template.setUpdateId(userId);
//                template.setUpdateTime(LocalDateTime.now());
                this.baseMapper.updateById(template);
            }
            return true;
        } catch (Exception e) {
            log.error("开启/关闭模版异常", e);
            return false;
        }
    }

    /**
     * @description: 获取企业开启的模板
     * @param: [groupId]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate
     * @author wxb
     * @date: 2024/4/12 11:25
     */
    @Override
    public FranchiseesApprovalTemplate getDefaultTemplate(Integer groupId) {
        LambdaQueryWrapper<FranchiseesApprovalTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FranchiseesApprovalTemplate::getGroupId, groupId);
        queryWrapper.eq(FranchiseesApprovalTemplate::getIsOpen, 1);
        queryWrapper.eq(FranchiseesApprovalTemplate::getIsDeleted, 0);
        queryWrapper.orderByAsc(FranchiseesApprovalTemplate::getCreateTime);
        queryWrapper.last("limit 1");
        FranchiseesApprovalTemplate template = this.baseMapper.selectOne(queryWrapper);
        if (template == null) {
            template = this.getSystemTemplate();
            FranchiseesApprovalTemplateGroup templateGroup = franchiseesApprovalTemplateGroupService.getGroupTemplate(groupId, template.getId());
            // 没有改过系统模板
            if (templateGroup != null) {
                template.setTemplateName(templateGroup.getTemplateName());
                template.setTemplateDesc(templateGroup.getTemplateDesc());
                template.setIsOpen(templateGroup.getIsOpen());
                template.setUpdateId(templateGroup.getUpdateId());
                if (templateGroup.getUpdateId() != null) {
                    Users users = userService.getUsersById(templateGroup.getUpdateId());
                    template.setUpdateUser(users.getShowName());
                }
                template.setUpdateTime(templateGroup.getUpdateTime());
            }
        }
        // 获取模板最新版本号
        List<String> versionList = this.getVersionListByTemplateId(template.getId(), null, groupId);
        if (CollectionUtil.isNotEmpty(versionList)) {
            template.setVersion(versionList.get(0));
        }
        return template;
    }

    /**
     * @description: 获取企业的模板 包含系统模版
     * @param: [groupId]
     * @return: java.util.List<com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate>
     * @author wxb
     * @date: 2024/4/12 14:30
     */
    @Override
    public IPage<FranchiseesApprovalTemplate> getTemplateByGroupId(Integer pageSize, Integer pageNumber, Integer groupId, Integer open) {
        Page<FranchiseesApprovalTemplate> page = new Page<>(pageNumber, pageSize);
        return this.baseMapper.page(page, groupId, open);
    }

    /**
     * @description: 获取系统模板
     * @param: []
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate
     * @author wxb
     * @date: 2024/4/12 11:28
     */
    @Override
    public FranchiseesApprovalTemplate getSystemTemplate() {
        LambdaQueryWrapper<FranchiseesApprovalTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(FranchiseesApprovalTemplate::getGroupId);
        queryWrapper.last("limit 1");
        return this.baseMapper.selectOne(queryWrapper);
    }

    /**
     * @description: 获取模板字段
     * @param: [templateId, groupId]
     * @return: com.ovopark.organize.server.model.vo.FranchiseesApprovalTemplateVo
     * @author wxb
     * @date: 2024/4/12 14:50
     */
    @Override
    public FranchiseesApprovalTemplate getTemplateFields(Integer templateId, Integer groupId, String version) {
        if (templateId != null) {
            // 模板
            FranchiseesApprovalTemplate template = this.getTemplateById(templateId, groupId);
            if (template != null) {
                List<String> versions = this.getVersionListByTemplateId(template.getId(), template.getVersion(), template.getGroupId());
                template.setVersion(CollectionUtil.isNotEmpty(versions) ? versions.get(0) : null);
                template.setVersions(versions);
                // 获取分组
                List<FranchiseesApprovalTemplateSection> sectionList = franchiseesApprovalTemplateSectionService.getSectionListByTemplateId(template, version);
                template.setSectionList(sectionList);
                return template;
            }
        }
        return null;
    }

    /**
     * @description: 获取模板配置
     * @param: [templateId, groupId]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate
     * @author wxb
     * @date: 2024/6/1 22:39
     */
    @Override
    public FranchiseesApprovalTemplate getTemplateConf(Integer templateId, Integer groupId, String version) {
        if (templateId != null) {
            // 模板
            FranchiseesApprovalTemplate template = this.getTemplateById(templateId, groupId);
            if (template != null) {
                // 获取分组
                List<FranchiseesApprovalTemplateSection> sectionList = franchiseesApprovalTemplateSectionService.getSectionListByTemplateId(template, version);
                template.setSectionList(sectionList);
                return template;
            }
        }
        return null;
    }

    /**
     * @description: 保存模板字段
     * @param: [vo]
     * @return: void
     * @author wxb
     * @date: 2024/4/16 16:46
     */
    @Override
    public void saveTemplateFields(FranchiseesApprovalTemplate template) {
        if (template == null) {
            return;
        }
        // 模板
        template = this.saveTemplate(template);
        if (template != null) {
            // 保存分组
            List<FranchiseesApprovalTemplateSection> sectionList = template.getSectionList();
            if (CollectionUtil.isNotEmpty(sectionList)) {
                for (FranchiseesApprovalTemplateSection section : sectionList) {
                    section.setTemplateId(template.getId());
                    section.setName(template.getTemplateName());
                }
                franchiseesApprovalTemplateSectionService.batchSaveSectionList(sectionList);
            }
        }
    }

    /**
     * @description: 保存模板配置
     * @param: [sectionList, userId]
     * @return: java.util.List<com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplateSection>
     * @author wxb
     * @date: 2024/5/31 21:11
     */
    @Override
    public List<FranchiseesApprovalTemplateSection> saveTemplateFieldsConf(FranchiseesApprovalTemplate template, Integer userId) {
        List<FranchiseesApprovalTemplateSection> sectionList = template.getSectionList();
        if (CollectionUtils.isEmpty(sectionList)) {
            throw new CommonException("请传递参数");
        }
        // 模板ID
        Integer templateId = template.getId();
        // 版本号
        String version = template.getVersion();
        // 企业ID
        Integer groupId = template.getGroupId();
        // 更新模板时间
        FranchiseesApprovalTemplate updateTemplate = this.getTemplateById(templateId, groupId);
        // 处理模板
        if (updateTemplate != null) {
            if (updateTemplate.getGroupId() != null) {
                // 系统模板
                updateTemplate.setUpdateTime(LocalDateTime.now());
                updateTemplate.setUpdateId(userId);
                this.baseMapper.updateById(updateTemplate);
            } else {
                FranchiseesApprovalTemplateGroup templateGroup = new FranchiseesApprovalTemplateGroup();
                templateGroup.setTemplateId(templateId);
                templateGroup.setTemplateName(template.getTemplateName());
                templateGroup.setTemplateDesc(template.getTemplateDesc());
                templateGroup.setGroupId(groupId);
                templateGroup.setCreateId(userId);
                templateGroup.setCreateTime(LocalDateTime.now());
                templateGroup.setIsOpen(template.getIsOpen());
                // 企业模板
                franchiseesApprovalTemplateGroupService.saveTemplateGroup(templateGroup);
            }
        }
        // 查询数据库 得到的数据 只有外层控件
        List<FranchiseesApprovalTemplateSection> existSctionList = franchiseesApprovalTemplateSectionService.getSectionListByTemplateId(updateTemplate, version);
        // 校验
        if (sectionEquals(existSctionList, sectionList)) {
            return existSctionList;
        }
        // 新增
        franchiseesApprovalTemplateSectionService.insert(groupId, templateId, sectionList, userId);
        return sectionList;
    }

    // 校验分组
    public boolean sectionEquals(List<FranchiseesApprovalTemplateSection> existList, List<FranchiseesApprovalTemplateSection> newList) {
        if (existList == newList) {
            return true;
        }
        if (existList.size() != newList.size()) {
            return false;
        }
        int n = existList.size();
        int i = 0;
        while (n-- != 0) {
            if (!existList.get(i).equals(newList.get(i))) {
                return false;
            } else {
                List<FranchiseesApprovalTemplateField> existFieldList = franchiseesApprovalTemplateFieldService.getFieldListBySectionId(existList.get(i).getId());
                List<FranchiseesApprovalTemplateField> newFieldList = newList.get(i).getFields();
                boolean fieldEquals = fieldsEquals(existFieldList, newFieldList);
                if (!fieldEquals) {
                    return false;
                }
            }
            i++;
        }
        return true;
    }

    // 校验字段
    public boolean fieldsEquals(List<FranchiseesApprovalTemplateField> existList, List<FranchiseesApprovalTemplateField> newList) {
        if (existList == newList || (CollectionUtil.isEmpty(existList) && CollectionUtil.isEmpty(newList))) {
            return true;
        }
        if (existList.size() != newList.size()) {
            return false;
        }
        int n = existList.size();
        int i = 0;
        while (n-- != 0) {
            if (!existList.get(i).equals(newList.get(i))) {
                return false;
            } else {
                List<FranchiseesApprovalTemplateFieldSelect> existSelectList = existList.get(i).getFieldSelectList();
                List<FranchiseesApprovalTemplateFieldSelect> newSelectList = newList.get(i).getFieldSelectList();
                boolean selectEquals = selectEquals(existSelectList, newSelectList);
                if (!selectEquals) {
                    return false;
                }
            }
            i++;
        }
        return true;
    }

    // 校验选项
    public boolean selectEquals(List<FranchiseesApprovalTemplateFieldSelect> existList, List<FranchiseesApprovalTemplateFieldSelect> newList) {
        if (existList == newList || (CollectionUtil.isEmpty(existList) && CollectionUtil.isEmpty(newList))) {
            return true;
        }
        if (existList.size() != newList.size()) {
            return false;
        }
        int n = existList.size();
        int i = 0;
        while (n-- != 0) {
            if (!existList.get(i).equals(newList.get(i))) {
                return false;
            } else {
                List<FranchiseesApprovalTemplateFieldSelectFill> existResource = existList.get(i).getResource();
                List<FranchiseesApprovalTemplateFieldSelectFill> newResource = newList.get(i).getResource();
                if (!fillEquals(existResource, newResource)) {
                    return false;
                }
            }
            i++;
        }
        return true;
    }

    // 校验选项 填空
    public boolean fillEquals(List<FranchiseesApprovalTemplateFieldSelectFill> existList, List<FranchiseesApprovalTemplateFieldSelectFill> newList) {
        if (existList == newList || (CollectionUtil.isEmpty(existList) && CollectionUtil.isEmpty(newList))) {
            return true;
        }
        if (existList.size() != newList.size()) {
            return false;
        }
        int n = existList.size();
        int i = 0;
        while (n-- != 0) {
            if (!existList.get(i).equals(newList.get(i))) {
                return false;
            }
            i++;
        }
        return true;
    }

    /**
     * @description: 获取模板字段值
     * @param: [templateUserId, groupId]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalTemplate
     * @author wxb
     * @date: 2024/6/5 10:27
     */
    @Override
    public FranchiseesApprovalTemplate getTemplateFieldValue(Integer templateUserId, Integer groupId) {
        FranchiseesApprovalTemplate template = new FranchiseesApprovalTemplate();
        if (templateUserId != null) {
            List<FranchiseesApprovalTemplateSection> list = new ArrayList<>();
            // 获取templateUserId 用户获取字段值
            FranchiseesApprovalTemplateUser templateUser = franchiseesApprovalTemplateUserService.getById(templateUserId);
            if (templateUser != null) {
                template = this.getTemplateById(templateUser.getTemplateId(), groupId);
                template.setScore(templateUser.getScore());
                template.setVersion(templateUser.getVersion());
                // 获取分组
                List<FranchiseesApprovalTemplateSection> sectionList = franchiseesApprovalTemplateSectionService.getSectionListByTemplateId(template, templateUser.getVersion());
                if (CollectionUtil.isNotEmpty(sectionList)) {
                    sectionList.forEach(section -> {
                        // 获取字段
                        List<FranchiseesApprovalTemplateField> fields = section.getFields();
                        // 获取字段值
                        List<FranchiseesApprovalTemplateFieldValue> values = franchiseesApprovalTemplateFieldValueService.getFieldValueListByTemplateUserId(templateUser.getId(), groupId);
                        if (CollectionUtil.isNotEmpty(fields)) {
                            fields.forEach(field -> {
                                if (CollectionUtil.isNotEmpty(values)) {
                                    values.forEach(value -> {
                                        if (field.getId().equals(value.getFieldId())) {
                                            field.setValue(value.getValue());
                                            field.setValueName(value.getValueName());
                                        }
                                    });
                                }
                            });
                        }
                        list.add(section);
                    });
                }
                template.setSectionList(list);
                return template;
            }
        }
        return null;
    }

    @Override
    public List<FranchiseesApprovalTemplate> batchGetTemplateList(List<Integer> templateIdList, Integer groupId) {
        List<FranchiseesApprovalTemplate> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(templateIdList)) {
            // 系统模板
            Integer systemTemplateId = 1;
            if (templateIdList.contains(systemTemplateId)) {
                FranchiseesApprovalTemplate systemTemplate = this.getSystemTemplate();
                list.add(systemTemplate);
                templateIdList.remove(systemTemplateId);
            }
            if (!CollectionUtil.isEmpty(templateIdList)) {
                LambdaQueryWrapper<FranchiseesApprovalTemplate> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(FranchiseesApprovalTemplate::getId, templateIdList);
                queryWrapper.eq(FranchiseesApprovalTemplate::getGroupId, groupId);
                queryWrapper.eq(FranchiseesApprovalTemplate::getIsDeleted, 0);
                List<FranchiseesApprovalTemplate> templateList = this.baseMapper.selectList(queryWrapper);
                if (CollectionUtil.isNotEmpty(templateList)) {
                    for (FranchiseesApprovalTemplate template : templateList) {
                        list.add(template);
                    }
                }
            }
        }
        return list;
    }

    /**
     * @description: 逻辑删除
     * @param: [id]
     * @return: void
     * @author wxb
     * @date: 2024/4/25 15:13
     */
    @Override
    public void deleteById(Integer id) {
        if (id != null) {
            FranchiseesApprovalTemplate template = this.baseMapper.selectById(id);
            if (template == null) {
                throw new CommonException("模板不存在");
            }
            if (template.getGroupId() != null) {
                template.setIsDeleted(1);
                this.baseMapper.updateById(template);
            }
        }
    }

    /**
     * @description: 获取版本号
     * @param: [templateId, versions, groupId]
     * @return: java.util.List<java.lang.String>
     * @author wxb
     * @date: 2024/6/1 13:10
     */
    @Override
    public List<String> getVersionListByTemplateId(Integer templateId, String version, Integer groupId) {
        FranchiseesApprovalTemplate template = this.getTemplateById(templateId, groupId);
        if (template == null) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<FranchiseesApprovalTemplateSection> queryWrapper = new LambdaQueryWrapper<>();
        if (groupId != null) {
            queryWrapper.eq(FranchiseesApprovalTemplateSection::getGroupId, groupId);
        } else {
            queryWrapper.isNull(FranchiseesApprovalTemplateSection::getGroupId);
        }
        queryWrapper.eq(FranchiseesApprovalTemplateSection::getTemplateId, templateId);
        if (StringUtils.isNotEmpty(version)) {
            queryWrapper.like(FranchiseesApprovalTemplateSection::getVersion, version);
        }
        queryWrapper.groupBy(FranchiseesApprovalTemplateSection::getVersion);
        queryWrapper.orderByDesc(FranchiseesApprovalTemplateSection::getVersion);
        List<FranchiseesApprovalTemplateSection> sectionList = franchiseesApprovalTemplateSectionMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(sectionList)) {
            return sectionList.stream().map(FranchiseesApprovalTemplateSection::getVersion).collect(Collectors.toList());
        } else {
            return Lists.newArrayList();
        }
    }

    /**
     * @description: 校验模板名称是否重复
     * @param: [enterpriseId, templateName]
     * @return: boolean
     * @author wxb
     * @date: 2024/6/6 15:52
     */
    @Override
    public List<FranchiseesApprovalTemplate> hasTemplateName(Integer groupId, String templateName) {
        if (groupId != null && StringUtils.isNotEmpty(templateName)) {
            LambdaQueryWrapper<FranchiseesApprovalTemplate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FranchiseesApprovalTemplate::getTemplateName, templateName).eq(FranchiseesApprovalTemplate::getIsDeleted, 0);
            queryWrapper.and(i -> i.eq(FranchiseesApprovalTemplate::getGroupId, groupId).or().isNull(FranchiseesApprovalTemplate::getGroupId));
            List<FranchiseesApprovalTemplate> templateList = this.baseMapper.selectList(queryWrapper);
            return templateList;
        }
        return Lists.newArrayList();
    }

}
